// draggable.js
let isDragging = false
// 存储所有dom信息
let elements=[]
// 存储当前获取的dom信息
let element

const isPermitHanlder = (event)=>{
  // 判断边距是否小于5
  return event.offsetX > 5 && event.offsetY > 5 &&  (element.dom.clientHeight - event.offsetY) > 5 && (element.dom.clientWidth - event.offsetX) > 5
}
const handleMouseDown = (event) => {
    if(event.button!=0) return
    element = elements.filter(e=> {
      return e.dom.contains(event.target)
    })[0]
    element.initialX = event.clientX - element.currentX
    element.initialY = event.clientY - element.currentY

    isDragging = element&&isPermitHanlder(event)?true:false
}

const handleMouseMove = (event) => {
  if(event.button!=0) return
  if (isDragging && event && event.button==0) {
    event.preventDefault()
    element.currentX = event.clientX - element.initialX
    element.currentY = event.clientY - element.initialY
    element.dom.style.transform = `translate3d(${element.currentX}px, ${element.currentY}px, 0)`
  }
}

const handleMouseUp = (event) => {
  if(event.button!=0||!isDragging) return
  element.initialX = element.currentX
  element.initialY = element.currentY
  elements.forEach(e=> {
    if(e.dom == element.dom){
      e = element
    }
  })
  isDragging = false
}

const handleMouseLeave = () => {
    isDragging = false
}
const draggable = {
  mounted(el) {
    // 存贮dom信息
    let obj = {
      dom: el,
      currentX: 0,
      currentY: 0,
      initialX: 0,
      initialY: 0,
    }
    elements.push(obj)
    el.addEventListener('mousedown', handleMouseDown)
    el.addEventListener('mousemove', handleMouseMove)
    el.addEventListener('mouseup', handleMouseUp)
    el.addEventListener('mouseleave', handleMouseLeave)
  },
  beforeUnmount(el){
    let arr = elements.filter(e=>{
      return e!=el
    })
    elements = arr
    el.removeEventListener('mousedown', handleMouseDown)
    el.removeEventListener('mousemove', handleMouseMove)
    el.removeEventListener('mouseup', handleMouseUp)
    el.removeEventListener('mouseleave', handleMouseLeave)
  }
}

export default draggable